package shiro_study;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.util.ThreadContext;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class T {
	
	Logger log = LoggerFactory.getLogger(getClass());
	
	Subject subject = null;
	
	@Before
	public void before() {
		Factory<SecurityManager> factory = 
				new IniSecurityManagerFactory("classpath:shiro-jdbc-realm.ini");
		SecurityManager securityManager = factory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);
		subject = SecurityUtils.getSubject();
	}
	
	@Test
	public void testHelloworld() {
		
		UsernamePasswordToken token = new UsernamePasswordToken("zhang", "123");
		try {
			subject.login(token);
			log.info( "User [" + subject.getPrincipal() + "] logged in successfully." );
		} catch (AuthenticationException e) {
			System.out.println(e);
		}
	}
		
	@After
	public void after() {
		Assert.assertEquals(true, subject.isAuthenticated()); // 断言用户已经登录
		subject.logout();
		ThreadContext.unbindSubject();
	}
	
}
